Namespace Forms
    Friend Class frmGlobalVars

        Private m_newcar As CarBase
        Private m_ptArray As Byte()
        Private m_ptVars As Vars = Nothing
        Private m_ptBVars As BVars = Nothing
        Private m_key As String = ""

        Friend Event RefreshMenuItems As System.EventHandler

        ''' <summary>
        ''' Create a new variables lookup
        ''' </summary>
        ''' <param name="Car">carbase with the map data</param>
        ''' <param name="Data">Data for the variables</param>
        ''' <param name="Vars">variables</param>
        ''' <remarks></remarks>
        Sub New(ByRef Car As CarBase, ByRef Data As Byte(), ByRef Vars As Vars)
            MyBase.New()

            Me.InitializeComponent()

            m_newcar = Car
            m_ptArray = Data
            m_ptVars = Vars

            global_populate(m_ptVars)
        End Sub

        ''' <summary>
        ''' BikiRom Variables
        ''' </summary>
        ''' <param name="Car"></param>
        ''' <param name="Vars"></param>
        ''' <remarks></remarks>
        Sub New(ByRef Car As CarBase, ByRef Vars As BVars, Optional ByVal Key As String = "")
            MyBase.New()

            Me.InitializeComponent()

            m_newcar = Car
            m_ptArray = Me.m_newcar.getBikSettings.Data
            m_ptBVars = Vars
            m_key = Key

            global_populate(m_ptBVars, m_key)
        End Sub

        ''' <summary>
        ''' Causes the current form to refresh all its values
        ''' </summary>
        ''' <remarks></remarks>
        Sub Reload()
            If IsNothing(Me.m_ptBVars) Then
                global_populate(m_ptVars)
            Else
                global_populate(m_ptBVars, m_key)
            End If
        End Sub

        Private Sub global_populate(ByRef Vars As BVars, Optional ByVal Key As String = "")
            RemoveHandler Me.dGlobal.CellValueChanged, AddressOf dGlobal_ValueChanges
            RemoveHandler dGlobal.CellValueChanged, AddressOf dGlobal_BValueChanges
            RemoveHandler dGlobal.KeyPress, AddressOf dGlobal_KeyPress
            Try
                Dim objVars() As BVar = Vars.getAsArray(Key)
                dGlobal.Rows.Clear()
                dGlobal.Columns(1).Visible = False
                dGlobal.Columns(2).Visible = False
                dGlobal.Columns("Formula").Visible = True
                dGlobal.Enabled = True
                If Not IsNothing(objVars) AndAlso objVars.Length > 0 Then
                    For Each var As BVar In objVars
                        With dGlobal
                            .RowCount += 1
                            .Item("colName", .RowCount - 1).Value = var.Name
                            .Item("colName", .RowCount - 1).ReadOnly = True
                            .Item("Formula", .RowCount - 1).Value = var.ValueTxt
                            .Item("Formula", .RowCount - 1).ReadOnly = False
                        End With
                    Next
                End If
            Catch ex As Exception
            Finally
                AddHandler dGlobal.CellValueChanged, AddressOf dGlobal_BValueChanges
            End Try
        End Sub
        Private Sub global_populate(ByRef f_var As Vars)
            RemoveHandler dGlobal.CellValueChanged, AddressOf dGlobal_ValueChanges
            RemoveHandler dGlobal.CellValueChanged, AddressOf dGlobal_BValueChanges
            Try
                Dim f_vars() As Var = f_var.getAsArray
                Dim f_cell As DataGridViewCell
                dGlobal.Rows.Clear()
                dGlobal.Columns(1).Visible = True
                dGlobal.Columns(2).Visible = True
                dGlobal.Columns("Formula").Visible = False
                dGlobal.Enabled = True
                If Not IsNothing(f_var) Then
                    If f_var.count >= 1 Then
                        For Each vari As Var In f_vars
                            With dGlobal
                                .RowCount += 1
                                f_cell = .Item(2, .RowCount - 1)
                                '------- Initial row settings
                                .Item(0, .RowCount - 1).Value = vari.Name
                                .Item(0, .RowCount - 1).ReadOnly = True
                                If Not IsNothing(vari.Description) Then .Item(1, .RowCount - 1).Value = vari.Description.Description
                                .Item(1, .RowCount - 1).ReadOnly = True
                                .Rows(.RowCount - 1).Tag = vari
                                .Item(2, .RowCount - 1).ToolTipText = "Dbl click to edit"

                                If Not IsNothing(vari.SelectionValues) Then '----- Selection combo box
                                    Dim f_cellCombo As New States.DataGridViewComboBoxCell2
                                    f_cellCombo.Items.AddRange(vari.SelectionValues)
                                    f_cellCombo.SelectedValue = vari.getValue(m_ptArray)
                                    .Item(2, .RowCount - 1) = f_cellCombo
                                    .Item(2, .RowCount - 1).ReadOnly = False
                                ElseIf vari.BitSize = 1 Then ' ------------------- Selection check box
                                    .Item(2, .RowCount - 1) = New DataGridViewCheckBoxCell
                                    .Item(2, .RowCount - 1).Value = vari.getValue(m_ptArray)
                                ElseIf vari.BitSize = 0 Then
                                    .Item(2, .RowCount - 1) = New DataGridViewTextBoxCell
                                    .Item(2, .RowCount - 1).Value = vari.getValue(m_ptArray)
                                Else ' ------------------------------------------- Value Box
                                    If vari.Multiplier Mod 1 <> 0 Or vari.BitSize = 32 Then
                                        .Item(2, .RowCount - 1).Style.Format = "" '"N6"
                                    Else
                                        .Item(2, .RowCount - 1).Style.Format = "N0"
                                    End If
                                    .Item(2, .RowCount - 1).ReadOnly = False
                                    .Item(2, .RowCount - 1).Value = vari.getValue(m_ptArray)
                                End If

                            End With
                        Next
                    End If
                End If
            Catch
            Finally
                AddHandler dGlobal.CellValueChanged, AddressOf dGlobal_ValueChanges
                AddHandler dGlobal.KeyPress, AddressOf dGlobal_KeyPress
            End Try
        End Sub
        ''' <summary>
        ''' BikiRom Values changed in primary grid
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub dGlobal_BValueChanges(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            If e.RowIndex >= 0 And Not IsNothing(m_newcar) AndAlso Not IsNothing(m_ptBVars) Then
                Dim f_sender As DataGridView = CType(sender, DataGridView)
                Dim objVar As BVar = m_ptBVars.getByName(f_sender.Item("colName", e.RowIndex).Value)
                If Not IsNothing(objVar) Then
                    objVar.ValueTxt = f_sender("Formula", e.RowIndex).Value
                    If objVar.ValueTxt.Length > 0 Then
                        Dim nPosition As UInt16 = 0
                        Dim nValue As Single = 0
                        Dim nCount As Integer = -1
                        Dim arrBytes((BikSettings.nAUbytesPerUnit * BikSettings.nAUCount) - 1) As Byte
                        For i As Integer = 0 To arrBytes.Length - 1
                            arrBytes(i) = &HFF
                        Next

                        Try
                            Dim objAU As New ALUUnit.node(objVar.ValueTxt, nPosition, Nothing, 0, objVar.AdditionalValue)

                            objAU.Clean()
                            objAU.Assign(nCount)
                            objAU.Output(arrBytes)

                            Array.Copy(arrBytes, 0, m_newcar.getBikSettings.getData, CLng(objVar.Value), BikSettings.nAUbytesPerUnit * (objAU.Units + 1))

                            Err_message("Equation Compiled, save and upload to apply", message_type.MSG_Infomation)
                        Catch ex As ALUUnit.ArathmaticUnit_Exception
                            Err_message(ex.Description & ":" & ex.Location, message_type.MSG_Warning)
                            ' Catch
                            Err_message("Unknown error", message_type.MSG_Error)
                        End Try
                    End If
                Else
                    Err_message("Variable not set, File closed or not open")
                End If
                '' Refresh this value
                f_sender("Formula", e.RowIndex).Value = objVar.ValueTxt
            End If
        End Sub
        ''' <summary>
        ''' Normal Varaibles change din primary grid
        ''' </summary>
        ''' <param name="sender"></param>
        ''' <param name="e"></param>
        ''' <remarks></remarks>
        Private Sub dGlobal_ValueChanges(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
            If e.RowIndex >= 0 Then
                Dim f_sender As DataGridView = CType(sender, DataGridView)
                Dim var As Var = CType(f_sender.Rows(e.RowIndex).Tag, Var)
                If IsNothing(dGlobal.Item(2, e.RowIndex).Value) Then
                    dGlobal.Item(2, e.RowIndex).Value = "0"
                End If
                If Not IsNothing(var) And Not IsNothing(m_newcar) Then
                    If e.ColumnIndex = 2 Then
                        If f_sender.Item(e.ColumnIndex, e.RowIndex).GetType Is GetType(States.DataGridViewComboBoxCell2) Then
                            Dim f_cell As States.DataGridViewComboBoxCell2 = CType(f_sender.Item(e.ColumnIndex, e.RowIndex), States.DataGridViewComboBoxCell2)
                            var.SetValue(m_ptArray, f_cell.SelectedValue)
                            f_cell.SelectedValue = var.getValue(m_ptArray)
                        ElseIf dGlobal.Item(2, e.RowIndex).Value.GetType Is GetType(Boolean) Then
                            If dGlobal.Item(2, e.RowIndex).Value Then
                                var.SetValue(m_ptArray, 1)
                            Else
                                var.SetValue(m_ptArray, 0)
                            End If
                        Else
                            var.SetValue(m_ptArray, dGlobal.Item(2, e.RowIndex).Value.ToString.Replace(",", ""))
                        End If
                    End If
                    If var.b_reloadMenu Then
                        RaiseEvent RefreshMenuItems(Me, New System.EventArgs())
                        'menu_Populate(m_newcar)
                        'boxGlobal.Text = m_ptSubConfig.Name & " - " & m_ptVars.Description
                    Else
                        global_populate(m_ptVars)
                    End If

                    'If m_ptArray Is m_newCar.CurrentMap Then
                    '    Try
                    '        If m_live Then
                    '            tmrEmulator.Enabled = False
                    '            Dim f_emuSetting As BVar = m_newCar.getConfig.getBikiVars.getByName("EMU")
                    '            If Not IsNothing(f_emuSetting) Then
                    '                Dim f_emudata As Emulator
                    '                f_emudata = New Emulator(m_ptArray, var.Address, 16, var.Address, f_emuSetting, 1, True)
                    '                Dim f_wait As Integer = 0

                    '                If thread_Check(threadAction.TH_EMUALTOR) Then
                    '                    thread_Add(threadAction.TH_EMUALTOR)
                    '                    bwEmulator.RunWorkerAsync(f_emudata)
                    '                Else
                    '                    m_cmdQueue.Enqueue(New Threads.QueueObj(f_emudata, threadAction.TH_EMUALTOR, BikiAction.BK_ALL))
                    '                End If
                    '            End If
                    '        End If
                    '    Catch
                    '        Err_message(Err.Description)
                    '    End Try
                    '    ' --------------------------------------------------------------------------------------------------------------------
                    'Else ' Is a BikiRom Settings Variable.. Do upload and refresh here

                    'End If
                Else
                    Err_message("Error Setting Variable Value, try again")
                End If
            End If
        End Sub
        Private Sub dGlobal_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
            Dim f_sender As DataGridView = CType(sender, DataGridView)
            If Not IsNothing(m_newcar) Then
                If Not IsNothing(f_sender.SelectedRows) Then
                    Dim var As Var = CType(f_sender.Rows(f_sender.SelectedRows(0).Cells(0).RowIndex).Tag, Var)
                    '.rm_ptVars.getByName(sender.SelectedRows.Item(0).Cells(0).Value)
                    ' -------------------------------------------------------------------------------------------------------------------------
                    If Not IsNothing(var) Then
                        Dim f_mult As Double
                        Dim f_strInput As String
                        If e.KeyChar = Chr(42) Or e.KeyChar = Chr(45) Or e.KeyChar = Chr(43) Or e.KeyChar = Chr(47) Then
                            Try
                                f_strInput = InputBox("Value for Operator '" & e.KeyChar & " on - " & var.Name & Chr(13) & _
                            "Description: " & var.Description.Description & Chr(13) & _
                            "Old Value  : " & Str(var.getValue(m_ptArray)), e.KeyChar)
                                If f_strInput = "" Then Exit Sub
                                f_mult = Val(f_strInput)
                                Select Case e.KeyChar
                                    Case Chr(42)
                                        var.SetValue(m_ptArray, var.getValue(m_ptArray) * f_mult)
                                    Case Chr(45)
                                        var.SetValue(m_ptArray, var.getValue(m_ptArray) - f_mult)
                                    Case Chr(43)
                                        var.SetValue(m_ptArray, var.getValue(m_ptArray) + f_mult)
                                    Case Chr(47)
                                        If f_mult <> 0 Then
                                            var.SetValue(m_ptArray, var.getValue(m_ptArray) / f_mult)
                                        End If
                                End Select
                            Catch
                            End Try
                            ' -------------------------------------------------------------------------------------------------------------------------
                        ElseIf e.KeyChar = Chr(32) Then
                            Try
                                f_strInput = InputBox("New Value for - " & var.Name & Chr(13) & _
                                            "Description: " & var.Description.Description & Chr(13) & _
                                            "Old Value  : " & Str(var.getValue(m_ptArray)), "Input New Value", Str(var.getValue(m_ptArray)))
                                If f_strInput = "" Then Exit Sub
                                If Val(f_strInput) >= 0 Then
                                    var.SetValue(m_ptArray, Val(f_strInput))
                                End If
                            Catch
                            End Try
                        End If
                        global_populate(m_ptVars)
                        ' -------------------------------------------------------------------------------------------------------------------------
                    End If
                End If
            End If
        End Sub

        Public Function CompareTo(ByRef Vars As BVars) As Boolean
            If Me.m_ptBVars Is Vars Then
                Return True
            End If
            Return False
        End Function
        Public Function CompareTo(ByRef Vars As Vars, ByRef Data As Byte()) As Boolean
            If Me.m_ptVars Is Vars And Data Is m_ptArray Then
                Return True
            End If
            Return False
        End Function
    End Class

End Namespace
